//
//  TLRechargeHistoryViewController.m
//  WXReader
//
//  Created by huaya on 2025/3/21.
//  Copyright © 2025 Andrew. All rights reserved.
//

#import "TLRechargeHistoryViewController.h"
#import "HMSegmentedControl.h"
#import "TLRechargeHistoryTableViewCell.h"
#import "TLConsumptionTableViewCell.h"

#import "TLRechargeHistoryModel.h"

@interface TLRechargeHistoryViewController ()<UITableViewDelegate,UITableViewDataSource>
    
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) UIView *navView;
@property (nonatomic, strong) UILabel *navTitleLab;
@property (nonatomic, strong) HMSegmentedControl *segControl;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSNumber *pageNum;
@property (nonatomic, strong) NSNumber *pageSize;
@property (nonatomic, strong) NSMutableArray<TLRechargeHistoryModel *>* dataArr;
@end

@implementation TLRechargeHistoryViewController
-(NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [NSMutableArray new];
    }
    return _dataArr;
}
- (UIView *)navView{
    if (!_navView) {
        _navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, PUB_NAVBAR_HEIGHT)];
        [_navView setBackgroundColor:[UIColor whiteColor]];
        _backBtn = [[UIButton alloc] initWithFrame:CGRectMake(6, PUB_NAVBAR_HEIGHT - 28 - 6, 28, 28)];
        [_backBtn setImage:[UIImage imageNamed:@"tzxqy_fh"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navView addSubview:_backBtn];
        
        _navTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, PUB_NAVBAR_HEIGHT - 28 - 6, kScreenWidth, 28)];
        _navTitleLab.text = @"Transaction History";
        _navTitleLab.textColor = [UIColor colorWithHexString:@"#000000"];
        _navTitleLab.font = [UIFont systemFontOfSize:17 weight:UIFontWeightMedium];
        _navTitleLab.textAlignment = NSTextAlignmentCenter;
        [_navView addSubview:_navTitleLab];
        _navView.backgroundColor = [UIColor whiteColor];
        _navTitleLab.textColor = [UIColor blackColor];
    }
    return _navView;
}
- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.pageNum = @(1);
    self.pageSize = @(20);
    
    [self setUI];
    
    [self network];
}
- (void)setUI{
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:self.navView];
    [self.view addSubview:self.segControl];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.segControl.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    
    
    
}

- (HMSegmentedControl *)segControl{
    if (!_segControl) {
        _segControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"Top Up",@"Spending"]];
        _segControl.backgroundColor = UIColor.clearColor;
        _segControl.titleTextAttributes = @{NSFontAttributeName : BOLD_SYSTEM_FONT(16),
                                            NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#000000"]};
        _segControl.selectedTitleTextAttributes = @{NSFontAttributeName : BOLD_SYSTEM_FONT(16),
                                                    NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#9E6DFC"]};
        _segControl.selectionIndicatorHeight = 2.0f;
        _segControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
        _segControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
        _segControl.selectionIndicatorColor = [UIColor colorWithHexString:@"#9E6DFC"];
        
        _segControl.segmentWidthStyle = HMSegmentedControlSegmentWidthStyleFixed;
        
        _segControl.frame = CGRectMake(0, CGRectGetMaxY(self.navView.frame), 240, 40);
        
        _segControl.selectedSegmentIndex = self.selectedIndex;
        
        MJWeakSelf
        _segControl.indexChangeBlock = ^(NSInteger index) {
//            [weakSelf loadLastData];
            [weakSelf.tableView.mj_header beginRefreshing];
        };
    }
    return _segControl;
}
#pragma mark - table delegate - datasource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (_segControl.selectedSegmentIndex == 0) {
        TLRechargeHistoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TLRechargeHistoryTableViewCell"];
        
        if (self.dataArr.count>indexPath.row) {
            cell.model = self.dataArr[indexPath.row];
        }
        
        return cell;
    }else{
        TLConsumptionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TLConsumptionTableViewCell"];
        
        if (self.dataArr.count>indexPath.row) {
            cell.model = self.dataArr[indexPath.row];
        }
        
        return cell;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.segControl.selectedSegmentIndex==1) {
        return 100;
    }
    return 50;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArr.count;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

}
- (UITableView *)tableView{
    if (!_tableView) {
        UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width,MK_SCREEN_SAVE_BOTTOM_HEIGHT)];
        footView.backgroundColor = UIColor.clearColor;
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = UIColor.whiteColor;
        _tableView.tableFooterView = footView;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = YES;
        if (@available(iOS 15.0, *)) {
            self.tableView.sectionHeaderTopPadding = 0;
        }
        [_tableView registerNib:[UINib nibWithNibName:@"TLRechargeHistoryTableViewCell" bundle:nil] forCellReuseIdentifier:@"TLRechargeHistoryTableViewCell"];
        
        [_tableView registerNib:[UINib nibWithNibName:@"TLConsumptionTableViewCell" bundle:nil] forCellReuseIdentifier:@"TLConsumptionTableViewCell"];
        
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadLastData)];
        header.lastUpdatedTimeLabel.hidden = YES;
        _tableView.mj_header = header;

        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    }
    return _tableView;
}
- (void)loadLastData{
    
    self.pageNum = [NSNumber numberWithInt:1];
    
    [self.dataArr removeAllObjects];
    
    [self network];
}
- (void)loadMoreData{
    
    self.pageNum = [NSNumber numberWithInt:(self.pageNum.intValue+1)];
    
    [self network];
}
- (void)network{
    
    _segControl.userInteractionEnabled = NO;
    if (_segControl.selectedSegmentIndex==0) {
        [self networkForRecords];
    }else{
        [self networkForConsumption];
    }
}
- (void)networkForConsumption{
    
    NSDictionary *param = @{
        @"pageNum":self.pageNum,
        @"pageSize":self.pageSize
    };
    
    
    
    [APIManager sendGetRequest:[APIURLManager getUserPaid] parameters:param model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        _segControl.userInteractionEnabled = YES;
        if (success) {
            
            NSArray *data = [TLRechargeHistoryModel mj_objectArrayWithKeyValuesArray:requestModel.data[@"records"]];
            
            [self.dataArr addObjectsFromArray:data];
            
            [self.tableView reloadData];
            
            [self.tableView.mj_header endRefreshing];
            
            if (data.count<self.pageSize.intValue) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self.tableView.mj_footer endRefreshing];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        NSLog(@"%@",error);
        _segControl.userInteractionEnabled = YES;
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }];
}
- (void)networkForRecords{
//    [self test];
    NSDictionary *param = @{
        @"pageNum":self.pageNum,
        @"pageSize":self.pageSize
    };
    
    [APIManager sendGetRequest:[APIURLManager getPaymentRecords] parameters:param model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        _segControl.userInteractionEnabled = YES;
        if (success) {
            
            NSArray *data = [TLRechargeHistoryModel mj_objectArrayWithKeyValuesArray:requestModel.data[@"records"]];
            
            [self.dataArr addObjectsFromArray:data];
            
            [self.tableView reloadData];
            
            [self.tableView.mj_header endRefreshing];
            
            if (data.count<self.pageSize.intValue) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self.tableView.mj_footer endRefreshing];
            }
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        NSLog(@"%@",error);
        _segControl.userInteractionEnabled = YES;
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }];
    
}

@end
